package com.sky.item.service.es.impl;

import com.alibaba.fastjson.JSON;
import com.sky.entity.ESDish;
import com.sky.item.service.es.DishServiceForES;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class DishServiceForESImpl implements DishServiceForES {

    @Autowired
    @Qualifier("elasticsearchClient")
    private RestHighLevelClient client;

    @Override
    public List<Long> searchByName(String name) throws IOException {
        SearchRequest searchRequest = new SearchRequest("dish");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MatchPhraseQueryBuilder matchPhraseQuery = QueryBuilders.matchPhraseQuery("name", name);
//        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", name);
        searchSourceBuilder.query(matchPhraseQuery);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        log.info(JSON.toJSONString(hits));
        List<Long> ids = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Long id =  Long.valueOf(sourceAsMap.get("id").toString());
            ids.add(id);
        }
        return ids;
    }

    /**
     * 添加文档
     *
     * @param id
     * @param name
     * @return
     */
    @Override
    public RestStatus insert(Long id, String name) throws IOException {
        IndexRequest request = new IndexRequest("dish");
        ESDish esDish = new ESDish(id, name);
        request.id(""+esDish.getId());
        request.timeout(TimeValue.timeValueMillis(2000));
        request.source(JSON.toJSONString(esDish), XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        log.info("add status:"+response.isFragment());
        log.info("document id: "+response.getId());
        log.info("response:"+response);
        return response.status();
    }

    @Override
    public RestStatus deleteById(Long id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("dish", "" + id);
        deleteRequest.timeout("1s");
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        return deleteResponse.status();
    }

    @Override
    public RestStatus updateById(Long id, String name) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("dish", "" + id);
        ESDish esDish = new ESDish(id, name);
        updateRequest.doc(JSON.toJSONString(esDish), XContentType.JSON);
        UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
        log.info("status: "+response.status());
        return response.status();
    }

    /**
     * 删除索引
     * @param indexName
     * @return
     * @throws IOException
     */
    @Override
    public Boolean deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("dish");
        AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);

        return response.isAcknowledged();
    }


    /**
     * 清空索引中的数据
     * @param indexName
     * @return
     */
    public Boolean deleteAll(String indexName) throws IOException {
        DeleteByQueryRequest request = new DeleteByQueryRequest(indexName);
        request.setQuery(QueryBuilders.matchAllQuery());
        BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);
        return response.isFragment();
    }


}
